package de.osmembrane.tools.xmlocalizr;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.jdom.Element;

public class XMLTreeObject {

	/**
	 * Reference to JDOM {@link Element}
	 */
	private Element reference;

	/**
	 * Map of all descriptions, e.g. "en" => "Test string"
	 */
	private Map<String, String> descs;

	/**
	 * Creates a new {@link XMLTreeObject} from a JDOM element. Finds out about
	 * all its localized descriptions.
	 * 
	 * @param reference
	 */
	public XMLTreeObject(Element reference) {
		this.reference = reference;

		this.descs = new HashMap<String, String>();

		for (Object o : reference.getChildren()) {
			if (o instanceof Element) {
				Element elt = (Element) o;
				if (elt.getName() == "description") {				
					descs.put(elt.getAttributeValue("lang"),
							elt.getValue());
				}
			}
		} /* for */
	}

	/**
	 * The localization for code code
	 * 
	 * @param code
	 * @return
	 */
	public String getLocalization(String code) {
		return descs.get(code);
	}

	/**
	 * Sets the localization for code to localiz
	 * 
	 * @param code
	 * @param localiz
	 */
	public void setLocalization(String code, String localiz) {
		descs.put(code, localiz);
	}
	
	public void updateDocument() {
		
		// remove old
		reference.removeChildren("description", reference.getNamespace());

		
		// insert new
		for (Entry<String, String> e : descs.entrySet()) {
			Element value = new Element("value", reference.getNamespace());
			value.setText(e.getValue());
			
			Element desc = new Element("description", reference.getNamespace());			
			desc.setAttribute("lang", e.getKey());
			desc.addContent(value);
			
			reference.addContent(desc);
		}
	}

	@Override
	public String toString() {
		return reference.getName() + " " + descs.keySet().toString();
	}

}
